<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <!-- 插入到 left 插槽位置 -->
        <template #left>
          <i class="el-icon-info" />
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <!-- 插入到 right 插槽位置 -->
        <template #right>
          <el-button
            type="primary"
            size="small"
            @click="$router.push('/import')"
          >导入excel</el-button>
          <el-button type="primary" size="small">导出excel</el-button>
          <!-- 新增员工按钮 -->
          <el-button
            type="primary"
            size="small"
            @click="showDialog"
          >新增员工</el-button>
        </template>
      </PageTools>
    </div>
    <el-card style="margin-top: 10px">
      <el-table :data="list" border>
        <el-table-column label="序号" width="60" type="index" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="头像">
          <template #default="scope">
            <img :src="scope.row.staffPhoto" style="width:100%;">
          </template>
        </el-table-column>
        <el-table-column label="工号" prop="workNumber" />
        <!-- <el-table-column label="聘用形式" prop="formOfEmployment" /> -->
        <el-table-column label="聘用形式">
          <template #default="{ row }">
            {{ hireMap[row.formOfEmployment] }}
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间">
          <template #default="{ row }">
            {{ formatDate(row.timeOfEntry) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button
              type="text"
              size="small"
              @click="toDetail(row.id)"
            >查看</el-button>
            <el-button type="text" size="small" @click="showAssignRole(row.id)">分配角色</el-button>
            <el-button
              type="text"
              size="small"
              @click="delEmployee(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination
          :current-page="params.page"
          :page-size="params.size"
          :total="total"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>

    <AddEmployee
      :visible="dialogVisible"
      @dialog-close="dialogClose"
      @fetch-employee-list="fetchEmployeeList"
    />

    <!-- 给员工分配角色弹窗 -->
    <el-dialog title="分配角色" :visible="assignRoleVisible" @close="assignRoleClose" @open="assignRoleOpen">
      <!-- 角色多选框 -->
      <!-- roleIds：选中的多选框中的 label 组成的数组 -->
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <!-- 按钮区域 -->
      <template #footer>
        <el-button size="small" @click="assignRoleClose">取消</el-button>
        <el-button type="primary" size="small" @click="submitAssginRoles">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// import PageTools from '@/components/PageTools'
import { getEmployeeList, delEmployee, assignRoles } from '@/api/employee'
import { getUserDetailById } from '@/api/user'
import { getRoleList } from '@/api/setting'
import dayjs from 'dayjs'
import AddEmployee from './AddEmployee'
export default {
  name: 'Employee',
  components: {
    AddEmployee
  },
  data() {
    return {
      // 员工列表数据
      list: [],
      params: {
        page: 1, // 当前页
        size: 10 // 每页条数
      },
      total: 0, // 总数
      // 定义聘用形式的枚举
      hireMap: {
        1: '正式',
        2: '非正式'
      },
      dialogVisible: false,
      // 控制分配角色弹窗的显示与隐藏
      assignRoleVisible: false,
      // 角色列表
      roleList: [],
      // 选中的角色 id 组成的数组
      roleIds: [],
      // 员工 id
      employeeId: ''
    }
  },
  created() {
    this.fetchEmployeeList()
  },
  methods: {
    async fetchEmployeeList() {
      const {
        data: { rows, total }
      } = await getEmployeeList(this.params)
      this.list = rows
      this.total = total
    },
    // 展示第几页，发生变化的回调
    handleCurrentChange(newPage) {
      this.params.page = newPage
      this.fetchEmployeeList()
    },
    // 格式化时间
    formatDate(value) {
      return dayjs(value).format('YYYY-MM-DD')
    },
    // 打开弹窗
    showDialog() {
      this.dialogVisible = true
    },
    // 弹窗关闭后，执行的回调
    dialogClose() {
      this.dialogVisible = false
    },
    // 删除员工
    delEmployee(id) {
      // 1. 询问用户
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // 2. 调用接口
          await delEmployee(id)
          // 3. 提示用户
          this.$message.success('删除员工成功')
          // 删除最后一页最后一条数据时，页数减 1
          if (this.list.length === 1 && this.params.page > 1) {
            this.params.page--
          }
          // 4. 刷新列表
          this.fetchEmployeeList()
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // 跳转到员工详情页，并传递参数
    toDetail(id) {
      this.$router.push({
        path: '/employeeDetail',
        query: {
          id
        }
      })
    },
    // 显示分配角色弹窗
    showAssignRole(id) {
      this.assignRoleVisible = true

      // 点击分配权限按钮，获取员工 id
      this.employeeId = id
    },
    // 分配角色弹窗关闭，执行的回调
    assignRoleClose() {
      this.assignRoleVisible = false
    },
    // 分配角色弹窗打开，执行的回调
    async assignRoleOpen() {
      // 获取角色列表数据
      // 因为该接口做了分页，我们为了获取全部角色，将 page 设置为 1，pagesize 设置为 100
      const res = await getRoleList({
        page: 1,
        pagesize: 100
      })
      this.roleList = res.data.rows

      // 在获取所有角色列表数据后，再获取该员工的已设置的角色
      const userDetail = await getUserDetailById(this.employeeId)
      console.log(userDetail)
      this.roleIds = userDetail.data.roleIds
    },
    // 分配权限
    async submitAssginRoles() {
      // 调用接口
      await assignRoles({
        id: this.employeeId,
        roleIds: this.roleIds
      })
      // 提示用户
      this.$message.success('分配角色成功')
      // 关闭弹窗
      this.assignRoleClose()
    }
  }
}
</script>

<style>
</style>
